<template>
	<sc-dialog
		v-model="visible"
		show-fullscreen
		destroy-on-close
		:title="`${titleMap[mode]}-${model.doc}`"
		width="70%"
		@close="close">
		<el-table ref="tableRef" row-key="id" :data="tableData" style="width: 100%; height: 100%;">
			<el-table-column type="index" width="30" align="center" />
			<el-table-column prop="content" label="点检项内容" align="center" />
			<el-table-column prop="standard" label="点检项标准" align="center" />
			<el-table-column prop="result" label="点检结果" align="center">
				<template #default="scope">
					<el-radio-group
						v-model="scope.row.result"
						:disabled="mode == 'list'"
						@change="saveResult(scope.row)">
						<el-radio label="NG" border>NG</el-radio>
						<el-radio label="OK" border>OK</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column prop="remark" label="描述" align="center">
				<template #default="scope">
					<el-input
						v-model="scope.row.remark"
						maxlength="512"
						show-word-limit
						:disabled="mode == 'list'"
						@change="saveRemark(scope.row)" />
				</template>
			</el-table-column>
		</el-table>
		<template #footer>
			<el-button @click="close">取 消</el-button>
			<el-button :loading="isSaveing" type="primary" :disabled="mode == 'list'" @click="submit">确 定</el-button>
		</template>
	</sc-dialog>
</template>

<script>
export default {
	emits: ['complete'],
	data() {
		return {
			mode: "list",
			titleMap: {
				list: "列表",
				edit: "编辑",
			},
			isSaveing: false,
			visible: false,
			docId: undefined,
			doc: '',
			model: {},
			tableData: [],
		};
	},
	methods: {
		async open(row) {
			this.model = row;

			// 状态：1=>已创建（允许编辑）;2=>已完成（只允许查看）
			if (row.status == 1) {
				this.mode = "edit";
			} else {
				this.mode = "list";
			}

			const resp = await this.$API.equipcheckdoc.model.get(row.id);
			this.tableData = resp.data.items;
			this.visible = true;
		},
		async saveResult(row) {
			let resp = await this.$API.equipcheckdocline.saveResult.put(row);
			if (resp.code != 200) {
				this.$alert(resp.message, "提示", { type: "error" });
			}
		},
		async saveRemark(row) {
			let resp = await this.$API.equipcheckdocline.saveRemark.put(row);
			if (resp.code != 200) {
				this.$alert(resp.message, "提示", { type: "error" });
			}
		},
		async submit() {
			if (this.tableData.some(s => s.result == '')) {
				this.$alert("请完成所有点检项再提交", "提示", { type: "error" });
				return;
			}

			this.isSaveing = true;
			const resp = await this.$API.equipcheckdoc.complete.put(this.model);
			this.isSaveing = false;
			if (resp.code == 200) {
				this.$emit("complete");
				this.$message.success("保存成功");
				this.visible = false;
			} else {
				this.$alert(resp.message, "提示", { type: "error" });
			}
		},
		close() {
			this.visible = false;

			this.model = {};
			this.tableData = [];
		},
	},
};
</script>
